package cn.ivicar.app.resource.customer;

import java.util.Date;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.InternalErrorException;
import cn.com.carsmart.exception.util.ExceptionResponseBuilder;
import cn.com.carsmart.ws.model.Customer;
import cn.com.carsmart.ws.util.CacheUtil;
import cn.ivicar.app.controller.util.DateUtil;
import cn.ivicar.message.push.controller.PushController;
import cn.ivicar.message.push.utils.EventCategoryEnum;
import cn.ivicar.passport.controller.PassportController;
import net.sf.json.JSONObject;

@Path("debug")
@RequestScoped
public class DebugReource {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(DebugReource.class);

	@Inject
	private PushController pushController;
	@Inject
	private PassportController passportController;

	/**
	 * 测试推送
	 * 
	 * @param params
	 * @return
	 */
	@Path("push")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response push(JSONObject params) {
		try {
			if (params.isEmpty() || params.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}
			String customerId = params.optString("customerId", "");
			String category = params.optString("category", "");
			String vehicleSerial = params.optString("vehicleSerial", "");
			String vehicleName = params.optString("vehicleName", "");
			String licensePlate = params.optString("licensePlate", "");

			validate("customerId", customerId);
			validate("category", category);
			validate("vehicleSerial", vehicleSerial);
			validate("vehicleName", vehicleName);
			validate("licensePlate", licensePlate);

			params.put("time", DateUtil.TIMEFORMATER1().format(new Date()));

			JSONObject extras = new JSONObject();
			extras.put("user_id", customerId);
			extras.put("car_serial", vehicleSerial);
			JSONObject type = new JSONObject();
			type.put("type", EventCategoryEnum.get(category).getIndex());
			extras.put("real_message", type.toString());
			extras.put("car_name", vehicleName);
			extras.put("time", params.optString("time", ""));
			extras.put("from", String.format("车辆名称:%s 车牌号:%s", params.optString("vehicleName", ""),
					params.optString("licensePlate", "")));
			extras.put("message", category.equals(EventCategoryEnum.SHAKE.getValue()) ? "车辆发生振动"
					: category.equals(EventCategoryEnum.VOLTAGE.getValue()) ? "车辆电压过低" : "");
			extras.put("car_license", licensePlate);
			String alert = extras.get("message") + "\n" + extras.get("from");
			extras.put("alert", alert);

			pushController.process(extras);

			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("推送出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("推送异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 测试推送
	 * 
	 * @param params
	 * @return
	 */
	@Path("push/test")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response pushTest(@QueryParam("customerId") String customerId, @QueryParam("category") String category,
			@QueryParam("vehicleSerial") String vehicleSerial, @QueryParam("vehicleName") String vehicleName,
			@QueryParam("licensePlate") String licensePlate) {
		try {

			validate("customerId", customerId);
			validate("category", category);
			validate("vehicleSerial", vehicleSerial);
			validate("vehicleName", vehicleName);
			validate("licensePlate", licensePlate);

			/*JSONObject params = new JSONObject();
			params.put("user_id", customerId);
			params.put("category", category);
			params.put("vehicleSerial", vehicleSerial);
			params.put("vehicleName", vehicleName);
			params.put("licensePlate", licensePlate);
			params.put("time", DateUtil.TIMEFORMATER1().format(new Date()));*/
			

            JSONObject extras = new JSONObject();
            extras.put("user_id", customerId);
            extras.put("car_serial", vehicleSerial);
            JSONObject type = new JSONObject();
            type.put("type", EventCategoryEnum.get(category).getIndex());
            extras.put("real_message", type.toString());
            extras.put("car_name", vehicleName);
            extras.put("time", DateUtil.TIMEFORMATER1().format(new Date()));
            extras.put("from", String.format("车辆名称:%s 车牌号:%s", vehicleName,
                    licensePlate));
            extras.put("message", category.equals(EventCategoryEnum.SHAKE.getValue()) ? "车辆发生振动"
                    : category.equals(EventCategoryEnum.VOLTAGE.getValue()) ? "车辆电压过低" : "");
            extras.put("car_license", licensePlate);
            String alert = extras.get("message") + "\n" + extras.get("from");
            extras.put("alert", alert);

			pushController.process(extras);

			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("测试推送出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("测试推送异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	private void validate(String key, String value) throws BadRequestException {
		if (StringUtils.isBlank(value)) {
			throw new BadRequestException("400", "key不能为空!");
		}
	}
	
	
	@Path("push/dev")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response pushDevTest(@QueryParam("mobile") String mobile, @QueryParam("category") String category,
			@QueryParam("vehicleSerial") String vehicleSerial, @QueryParam("vehicleName") String vehicleName,
			@QueryParam("licensePlate") String licensePlate) {
		try {

			validate("mobile", mobile);
			validate("category", category);
			validate("vehicleSerial", vehicleSerial);
			validate("vehicleName", vehicleName);
			validate("licensePlate", licensePlate);

            JSONObject extras = new JSONObject();
            Customer customer = passportController.getByMobile(mobile);
            if(customer == null){
            	throw new BadRequestException("400", "未注册");
            }
            extras.put("user_id", customer.getId());
            extras.put("car_serial", vehicleSerial);
            JSONObject type = new JSONObject();
            type.put("type", EventCategoryEnum.get(category).getIndex());
            extras.put("real_message", type.toString());
            extras.put("car_name", vehicleName);
            extras.put("time", DateUtil.TIMEFORMATER1().format(new Date()));
            extras.put("from", String.format("车辆名称:%s 车牌号:%s", vehicleName,
                    licensePlate));
            extras.put("message", category.equals(EventCategoryEnum.SHAKE.getValue()) ? "车辆发生振动"
                    : category.equals(EventCategoryEnum.VOLTAGE.getValue()) ? "车辆电压过低" : "");
            extras.put("car_license", licensePlate);
            String alert = extras.get("message") + "\n" + extras.get("from");
            extras.put("alert", alert);
            extras.put("apns", false);

			pushController.process(extras);

			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("测试推送出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("测试推送异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
	
	@Path("push/prod")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response pushProTest(@QueryParam("mobile") String mobile, @QueryParam("category") String category,
			@QueryParam("vehicleSerial") String vehicleSerial, @QueryParam("vehicleName") String vehicleName,
			@QueryParam("licensePlate") String licensePlate) {
		try {

			
			validate("mobile", mobile);
			validate("category", category);
			validate("vehicleSerial", vehicleSerial);
			validate("vehicleName", vehicleName);
			validate("licensePlate", licensePlate);

            JSONObject extras = new JSONObject();
            Customer customer = passportController.getByMobile(mobile);
            if(customer == null){
            	throw new BadRequestException("400", "未注册");
            }
            extras.put("user_id", customer.getId());
            extras.put("car_serial", vehicleSerial);
            JSONObject type = new JSONObject();
            type.put("type", EventCategoryEnum.get(category).getIndex());
            extras.put("real_message", type.toString());
            extras.put("car_name", vehicleName);
            extras.put("time", DateUtil.TIMEFORMATER1().format(new Date()));
            extras.put("from", String.format("车辆名称:%s 车牌号:%s", vehicleName,
                    licensePlate));
            extras.put("message", category.equals(EventCategoryEnum.SHAKE.getValue()) ? "车辆发生振动"
                    : category.equals(EventCategoryEnum.VOLTAGE.getValue()) ? "车辆电压过低" : "");
            extras.put("car_license", licensePlate);
            String alert = extras.get("message") + "\n" + extras.get("from");
            extras.put("alert", alert);
            extras.put("apns", true);
			pushController.process(extras);

			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("测试推送出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("测试推送异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
}